package com.tbi.graphcolouring.largestfirst;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;

import com.tbi.graphcolouring.BaseGraph;
import com.tbi.graphcolouring.BaseGraph.Node;

public class LargestFirstAlgorithm {
	private BaseGraph graph;
	private long time;
	private int rating;
	
	public LargestFirstAlgorithm(BaseGraph graph) {
		this.graph = graph;
		
		int size = 0;
		for(Node n : graph.getNodes()){
			n.setColor(0);
			
//			size += n.getConnections().size();
//			System.out.print(n.getID()+" : ");
//			for(Node conn : n.getConnections()){
//				System.out.print(conn.getID()+" ");
//			}
//			System.out.println();
		}
//		System.out.println("size: "+size);
	}
	
	public void doIt() {
		long start = System.currentTimeMillis();
		
		Collections.sort(graph.getNodes(), new Comparator<Node>() {
			@Override
			public int compare(Node o1, Node o2) {
				return o2.getConnections().size() - o1.getConnections().size();
			}
		});
		
		for(Node node : graph.getNodes()){
			while(!validate(node)){
				node.setColor(node.getColor()+1);
			}
		}
		
		this.time = System.currentTimeMillis() - start;
		
		int ratingModifier = 0;
		Set<Integer> colorCounter = new HashSet<>();
		for(Node node : graph.getNodes()){
			colorCounter.add(node.getColor());
			for(Node connected : node.getConnections()){
				if(connected.getColor() == node.getColor()){
					ratingModifier++;
				}
			}
		}
		
		this.rating = colorCounter.size() + ratingModifier;
		
//		System.out.println("kara: "+ratingModifier);
//		System.out.println(Arrays.toString(graph.getColors()));
	}
	
	public long getTime() {
		return time;
	}
	
	public int getRating() {
		return rating;
	}

	private boolean validate(Node node) {
		for(Node connectedNode : node.getConnections()){
			if(connectedNode.getColor() == node.getColor()){
				return false;
			}
		}
		
		return true;
	}
}
